﻿using Abp.ObjectMapping;
using Abp.UI;
using AVIS.OutBound.BookOrders;
using AVIS.OutBound.CarGroups.Dto;
using AVIS.OutBound.Cities;
using AVIS.OutBound.Orders;
using AVIS.OutBound.Orders.Dto;
using AVIS.OutBound.RateCodes;
using AVIS.OutBound.Stores;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace AVIS.OutBound.CarGroups
{
    /// <summary>
    /// 车组的应用服务类
    /// </summary>
    public class CarGroupAppService : OutBoundAppServiceBase, ICarGroupAppService
    {
        #region 构造函数
        private readonly ICarGroupManager _carGroupManager;
        private readonly IBookOrderManager _bookOrderManager;
        private readonly IObjectMapper _objectMapper;
        private readonly IRateCodeManager _RateCodeMananger;
        private readonly IStoreManager _storeManager;
        private readonly ICityManager _cityManager;

        /// <summary>
        /// 构造函数
        /// </summary>
        public CarGroupAppService(
              ICarGroupManager carGroupManager,
              IBookOrderManager bookOrderManager,
              IObjectMapper objectMapper,
              IRateCodeManager RateCodeMananger,
              IStoreManager storeManager,
              ICityManager cityManager)
        {
            _carGroupManager = carGroupManager;
            _bookOrderManager = bookOrderManager;
            _objectMapper = objectMapper;
            _RateCodeMananger = RateCodeMananger;
            _storeManager = storeManager;
            _cityManager = cityManager;
        }
        #endregion

        /// <summary>
        /// 查询指定预订单ID的车组列表接口
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public CarGroupsListOutput ListByOrderId(OrderIdInput input)
        {
            // 获取订单信息（预定单）
            var bookOrder = _bookOrderManager.GetBookOrder(input.orderId);

            // 获取满足订单的套餐价格代码（最新的4条）
            var RatePackages = _RateCodeMananger.GetRateCodesByOrder(bookOrder);

            // 特殊处理，只能显示最新的4个套餐
            if (RatePackages.Count > 4)
            {
                RatePackages.RemoveRange(4, RatePackages.Count - 4);
            }

            // 获取所有套餐的对应车组信息
            var list = new CarGroupsListOutput { OrderId = bookOrder.OrderId };
            var rs = _objectMapper.Map<AgentCarGroupsRequest>(bookOrder);
            foreach (var ratePackage in RatePackages)
            {
                // 1. 更改套餐价格编号
                rs.RateCode = ratePackage.Code;

                // 2.1 获取默认套餐的车组
                if (string.IsNullOrWhiteSpace(ratePackage.Code)
                    && ratePackage.Name == OutBoundConsts.DEFAULT_RATE_NAME) // 
                {
                    // 2. 获取车组信息并加入到 车型组的列表（CarGroupsListOutput）中
                    var listCarGroups = _carGroupManager.GetCarGroups(rs);
                    foreach (var cargroup in listCarGroups)
                    {
                        list.AddCarGroup(cargroup, ratePackage);
                    }

                    // 默认套餐不能为空车组
                    if (listCarGroups.Count == 0 && string.IsNullOrWhiteSpace(ratePackage.Code))
                    {
                        throw new UserFriendlyException("对不起，您所选的门店在此时间段内，无可用车组提供，请选择其他门店，谢谢。");
                    }
                }
                else
                {
                    try
                    {
                        // 2. 获取车组信息并加入到 车型组的列表（CarGroupsListOutput）中
                        var listCarGroups = _carGroupManager.GetCarGroups(rs);
                        foreach (var cargroup in listCarGroups)
                        {
                            list.AddCarGroup(cargroup, ratePackage);
                        }
                    }
                    catch (Exception ex)
                    {
                        // 非默认套餐出现异常只需要记录即可，不需要影响流程
                        Logger.Error($"获取套餐（{ratePackage.Code}）的车组数据时报错：{ex.Message}");
                    }
                }
            }

            // 
            RemoveDefaultRateCodeFromCoolCar(list, RatePackages);
            return list;
        }

        /// <summary>
        /// 查询指定预订单ID的车组增值服务接口
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public List<CarEquipmentItemDto> CarEquipmentsByOrderId(OrderIdInput input)
        {
            // 获取预订单信息
            var order = _bookOrderManager.GetBookOrder(input.orderId);

            // 将预订单信息中的增值服务转化为Dto，该增值服务在上一步提交选中车组中获取到。
            var products = _objectMapper.Map<List<CarEquipmentItemDto>>(order.CarGroup.CarEquipments);

            return products;
        }

        /// <summary>
        /// 移除CoolCar中的基础套餐（CoolCar的车组代码是2位字母）
        /// </summary>
        /// <returns></returns>
        private void RemoveDefaultRateCodeFromCoolCar(CarGroupsListOutput output, List<RateCode> ratePackages)
        {
            if (ConfigurationManager.AppSettings["CoolCarRemoveDefault"] != "1")
            {
                return;
            }

            // 排除基础套餐的套餐代码Code列表
            var rateCodes = ratePackages
                .Where(r => r.Code != OutBoundConsts.DEFAULT_RATE_CODE)
                .Select(r => r.Code)
                .ToArray();

            foreach (var item in output.CarGroupsList)
            {
                if (item.ModelCode.Trim().Length == 2)
                {
                    // 查出基础套餐
                    //（因为具体车组都是RateCode的，但是请求Wizard接口是采用基础套餐去请求的，
                    //  故不能采用等于的方式，而是采用不在非基础套餐里的都为基础套餐.
                    //  比如：基础套餐是“”，而获取到车组的RateCode为 C4.
                    // ）
                    var carGroup = item.CarGroups.FirstOrDefault(c => !rateCodes.Contains(c.RateCode));
                    if (carGroup != null)
                    {
                        item.CarGroups.Remove(carGroup);
                    }
                }
            }
        }
    }
}
